package com.example.gateway.proxy;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/api")
public class ProxyController {
    private final RestTemplate rest = new RestTemplate();

    @Value("${materials.url}")
    private String materialsUrl;

    @Value("${borrows.url}")
    private String borrowsUrl;

    // Generic pass-through helpers
    private ResponseEntity<String> forward(String base, String path, HttpMethod method, String body) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(body, headers);
        return rest.exchange(base + path, method, entity, String.class);
    }

    // Materials
    @GetMapping("/materials")
    public ResponseEntity<String> listMaterials() { return forward(materialsUrl, "/materials", HttpMethod.GET, null); }
    @GetMapping("/materials/{id}")
    public ResponseEntity<String> getMaterial(@PathVariable String id) { return forward(materialsUrl, "/materials/" + id, HttpMethod.GET, null); }
    @PostMapping("/materials")
    public ResponseEntity<String> createMaterial(@RequestBody String body) { return forward(materialsUrl, "/materials", HttpMethod.POST, body); }
    @PutMapping("/materials/{id}")
    public ResponseEntity<String> updateMaterial(@PathVariable String id, @RequestBody String body) { return forward(materialsUrl, "/materials/" + id, HttpMethod.PUT, body); }
    @DeleteMapping("/materials/{id}")
    public ResponseEntity<String> deleteMaterial(@PathVariable String id) { return forward(materialsUrl, "/materials/" + id, HttpMethod.DELETE, null); }

    // Borrows
    @GetMapping("/borrows")
    public ResponseEntity<String> listBorrows() { return forward(borrowsUrl, "/borrows", HttpMethod.GET, null); }
    @GetMapping("/borrows/{id}")
    public ResponseEntity<String> getBorrow(@PathVariable String id) { return forward(borrowsUrl, "/borrows/" + id, HttpMethod.GET, null); }
    @PostMapping("/borrows")
    public ResponseEntity<String> createBorrow(@RequestBody String body) { return forward(borrowsUrl, "/borrows", HttpMethod.POST, body); }
    @PutMapping("/borrows/{id}")
    public ResponseEntity<String> updateBorrow(@PathVariable String id, @RequestBody String body) { return forward(borrowsUrl, "/borrows/" + id, HttpMethod.PUT, body); }
    @DeleteMapping("/borrows/{id}")
    public ResponseEntity<String> deleteBorrow(@PathVariable String id) { return forward(borrowsUrl, "/borrows/" + id, HttpMethod.DELETE, null); }
}